package intelligentcity.loggers;

import intelligentcity.conf.Conf;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class TimeCounter extends Thread {

    private Map<Integer, Long> timeOfCarsPresence;
    private AtomicInteger numberOfCars;
    private AtomicLong totalTime;

    public TimeCounter() {
        super();
        timeOfCarsPresence = new ConcurrentHashMap<>();
        numberOfCars = new AtomicInteger(0);
        totalTime = new AtomicLong(0);
    }

    public void logPresence(int carId) {
        timeOfCarsPresence.put(carId, System.currentTimeMillis());
        numberOfCars.getAndIncrement();
    }

    public void logAbsence(int carId) {
        long startTime = timeOfCarsPresence.remove(carId);
        totalTime.addAndGet(System.currentTimeMillis() - startTime);

    }

    @Override
    public String toString() {
        return "TimeCounter [numberOfCars=" + numberOfCars.get() + ", totalTime=" + totalTime.get() / 1000 + "s]";
    }

    @Override
    public void run() {
        while (true) {
            System.out.println(this.getName() + " " + toString() + " " + "Ratio: "
                    + (float) ((int) (totalTime.get() / (double) numberOfCars.get()) / 10) / 100 + "s / car");
            Conf.stop(Conf.stopTime);
        }

    }
}
